import pytest
import os
import argparse
import json


# 使用绝对路径确保能找到测试文件
base_dir = os.path.dirname(os.path.abspath(__file__))
testfiles=[
    os.path.join(base_dir, "tests/test_before.py"),
    os.path.join(base_dir, "tests/test_insertClazz.py"),
    os.path.join(base_dir, "tests/test_insertStudent.py"),
    os.path.join(base_dir, "tests/test_insertCourseSchedule.py"),
    os.path.join(base_dir, "tests/test_insertAttendance.py"),
   # os.path.join(base_dir, "tests/test_er_diagram.py"),
   # os.path.join(base_dir, "tests/test_course_attendance.py"),
]

def calculate_score(json_report_path="report.json"):
    # 读取JSON测试报告
    with open(json_report_path) as f:
        report = json.load(f)
    
    total_score = 0
    passed_score = 0
    test_cases = []
    scores = []
    earned_scores = []

    # 收集测试数据
    for test in report.get("tests", []):
        test_cases.append(test["nodeid"].split("::")[-1])
        score = test.get("metadata", {}).get("score", 0)
        scores.append(str(score))
        earned = score if test["outcome"] == "passed" else 0
        earned_scores.append(str(earned))
        
        total_score += score
        passed_score += earned

    # 打印横向表格
    print("\n测试结果汇总:")
    print("测试用例\t｜" + "\t｜ ".join(test_cases))
    print("分值\t｜ " + "\t ｜ ".join(scores))
    print("得分\t｜ " + "\t ｜ ".join(earned_scores))
    
    # 写入Excel文件
    from openpyxl import Workbook
    wb = Workbook()
    ws = wb.active
    ws['B2'] = '分值'
    ws['B3'] = '得分'
    for col, score in enumerate(scores, start=2):
        ws.cell(row=2, column=col, value=int(score))
    for col, earned in enumerate(earned_scores, start=2):
        ws.cell(row=3, column=col, value=int(earned))
    wb.save(os.path.join(base_dir, "score.xlsx"))
    
    # 打印总分
    print(f"\n测试总分: {total_score}")
    print(f"获得分数: {passed_score}")
    print(f"得分率: {passed_score/total_score*100:.2f}%")

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument('--show-sql', action='store_true', help='显示SQL调试信息')
    args = parser.parse_args()
    
    # 构建pytest参数
    pytest_args = testfiles.copy()
    pytest_args.extend([
        "--json-report",
        "--json-report-file=report.json",
        "--json-report-indent=4",

    ])
    if args.show_sql:
        pytest_args.extend(["-v", "--log-cli-level=DEBUG"])
    
    # 添加pytest-metadata插件收集元数据
    # os.environ['PYTEST_ADDOPTS'] = '--metadata score -v'
    
    pytest.main(pytest_args)
    calculate_score()
